package com.example.list.jetpack;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.os.Bundle;

import com.example.list.R;

import java.util.concurrent.TimeUnit;

public class WorkManagerActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_manager);


        OneTimeWorkRequest oneTimeWorkRequest;
//传递给Work的参数
        Data sendData = new Data.
                Builder()
                .putString("data", "来自MainActivity的数据")
                .build();
//初始化请求对象request
        oneTimeWorkRequest = new OneTimeWorkRequest
                .Builder(MyWork.class)
                .setInputData(sendData)
                .build();
//添加回调更新
        WorkManager.getInstance(WorkManagerActivity.this)
                .getWorkInfoByIdLiveData(oneTimeWorkRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
            @Override
            public void onChanged(WorkInfo workInfo) {
                //注意这个方法会回调多次
                //要加这个判断
                if(workInfo.getState().isFinished()){
                    //执行完成的处理
                    //接受worker返回的结果
                    //这里的result与MMyWorker的result 需要一致
                    String result = workInfo.getOutputData().getString("result");
                }
            }
        });


        PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(MyWork.class,15, TimeUnit.SECONDS).build();
        WorkManager.getInstance(this).enqueue(periodicWorkRequest);

    }
}